      1  import java.util.ArrayList;

      2

      3  /**

      4     A tower containing disks in the Towers of Hanoi puzzle.

      5  */

      6  public class Tower

      7  {

      8     private ArrayList<Integer> disks;

      9

     10     /**

     11        Constructs a tower holding a given number of disks of decreasing size.

     12        @param ndisks the number of disks

     13     */

     14     public Tower(int ndisks)

     15     {

     16        disks = new ArrayList<Integer>();

     17        for (int d = ndisks; d >= 1; d--) { disks.add(d); }

     18     }

     19

     20     /**

     21        Removes the top disk from this tower.

     22        @return the size of the removed disk

     23     */

     24     public int remove()

     25     {

     26        return disks.remove(disks.size() - 1);

     27     }

     28

     29     /**

     30        Adds a disk to this tower.

     31        @param size the size of the disk to add

     32     */

     33     public void add(int size)

     34     {

     35        if (disks.size() > 0 && disks.get(disks.size() - 1) < size)

     36        {

     37           throw new IllegalStateException("Disk is too large");

     38        }

     39        disks.add(size);

     40     }

     41

     42     public String toString() { return disks.toString(); }

     43  }

     44